/**
 * @author yinghui.zhang  人员信息管理
 * 增加左侧机构树查询
 * 
 */
Ext.ns("cn.hls.web.action.dict.person");
var personView =cn.hls.web.action.dict.person.PersonView;

personView = function() {
	var orgTree, store, grid, formPanel, win, expander, addOrgTree, comboxWithTree, impFormPanel, impWin;
	var accountwin, accountPanel, 
    contextmenu, rolestore, rolegrid, secondGridStore, secondGrid, rolewin,
    grantmoduleTree, grantformPanel, grantwin, userstore, usergrid, usersecondGrid,
    usersecondGridStore, userwin,grantUserId;
	var fields =["id","name","gender","dutyNo","user","email","phone","remark","duty","org"];
	var sm =  new Ext.grid.CheckboxSelectionModel({header:'', singleSelect: true });
	return {
		init : function() {
			
			//------------------------------------------------- OrgTreePanel
			orgTree = this.createOrgTree();
			orgTree.on('click', function(node) {
				store.load( {
					params : {
						"page.start" : 0,
						"page.limit" : Ext.getCmp('page').pageSize
					}
				});
			});
			
			orgTree.root.select();
            
            //------------------------------------------------- store
            store = this.createStore();
            // 查询条件
			store.on('beforeload', function() {
					var selectModel = orgTree.getSelectionModel();
					var selectNode = selectModel.getSelectedNode();
					var companyId=personView.loadCompanyId(selectNode);
					var id = 0,name;
					id=selectNode.attributes.id;
					if(queryRole){
						name=Ext.getCmp('pname').getValue();
					}else{
						name=undefined;
					}
					this.baseParams = {
						//"page.colModel" : "id,name,username:user,userType,userid:user.id,phone",
						"name" : name,
						"org.id" : id,
						'companyId':companyId
					};
				});
            
			//------------------------------------------------- grid
			expander = this.createExpander();
			grid = this.createGrid();
			if(editRole){
				grid.on('rowdblclick', function(g, r, e) {
					personView.editInit();
				});
			}
			grid.on('render', function(grid) {  
			    var store = grid.getStore();  // Capture the Store.  
			    var view = grid.getView();    // Capture the GridView.  
			    grid.tip = new Ext.ToolTip({  
			        target: view.mainBody,    // The overall target element.  
			        //delegate: '.x-grid3-row', // Each grid row causes its own seperate show and hide.  
			        delegate: '.x-grid3-cell',
			        trackMouse: true,         // Moving within the row should not hide the tip.  
			        renderTo: document.body,  // Render immediately so that tip.body can be  
			        anchor: 'top',                           //  referenced prior to the first show.  
			        listeners: {              // Change content dynamically depending on which element  
			                                  //  triggered the show.  
			            beforeshow: function updateTipBody(tip) {  
			            	var rowIndex = view.findRowIndex(tip.triggerElement);  
	                        var cellIndex = view.findCellIndex(tip.triggerElement);  
			                var cellIndex = view.findCellIndex(tip.triggerElement);
			               if(cellIndex>1&& cellIndex<=8){
			                var cell = view.getCell(rowIndex, cellIndex);  
	                        tip.body.dom.innerHTML = cell.innerHTML;  
			               }else{
			            	   return false;
			               }
			            }  
			        }  
			    });  
			}); 
			// ------------------------------------------------- viewport
			new Ext.Viewport( {
				layout : 'border',
				items : [ {
					title : '所在单位',
					iconCls : 'layout_contentIcon',
					collapsible : true,
					width : 170,
					minSize : 170,
					maxSize : 170,
					split : true,
					region : 'west',
					autoScroll : true,
					items : [ orgTree ]
				}, {
					region : 'center',
					layout : 'fit',
					items : [ grid ]
				} ]
		   });
		   this.queryResItem();
			
		},
		
		createStore : function() {
			return new FrameWorkStore({
			     url : '/person/list.action',
			     fields : fields
		    });
		},
		/**根据选择节点获取企业单位编号**/
		loadCompanyId:function(selectNode){
			var parentNode=selectNode.parentNode;//获取上级模块
			if(parentNode==null){
				return undefined;
			}
			if(parentNode.parentNode==null){
				return selectNode.attributes.id;
			}else{
				/**递归获取组织机构所在的单位信息**/	
				do{
					if(parentNode.parentNode.id!="0"){//判断上级编号是否为根结点
						parentNode=parentNode.parentNode;
					}else{
						break;
					}
				}while(parentNode.id>0);
				return parentNode.attributes.id;
			}
		},
		createExpander : function() {
	       var xt = new Ext.Template('<div style="margin-left:3%">',
			                          '<table  class="displayTable">',
			                          '<tr><th>区域</th>',
			                          '<td><span id="area_{id}"></span>{id:this.setAreaValue}</td></tr>',
	                                  '</table></div>');
		
		    xt.setAreaValue = function(d){
		    	if (d == null) {
					return "";
				} else {
					//初始化值
					if(!cs.containsKey(d)){
						Ext.Ajax.request({
							url : cfg.cxt+'/person_load.do',
							success : function(response) {
								 var r = Ext.decode(response.responseText);
								 if(r.success){
								 	cs.add(d,r.areaNames);
								 	Ext.getDom('area_'+d).innerHTML =  r.areaNames;
								 } else {
									bangni.ajaxError(response);
								}
							},
							failure : bangni.ajaxError,
							params : {
								"person.id" : d
							}
						});
					}  else {
						return cs.map[d];
					}
				}
		    } 
		    
		    
	        return new Ext.grid.RowExpander({
	            enableCaching : false, //此处不能缓存，默认缓存会导致修改后bug
			    tpl : xt,
			    expandOnDblClick : false   // 屏蔽双击事件
		    });
		},
		
		createGrid : function() {
			return new ExtGrid(
					{

						region : 'center',
						store : store,
						sm : sm,
						columnLines : true,
//						plugins : expander,
						columns : [
//						        expander,
						        new Ext.grid.RowNumberer(),
						        sm,
						        { 
						        	sortable : true,
						        	autoWidth : true,
						        	dataIndex : "name",
						        	header : "用户名称",
						        	width : 50,
						        	align:'center'
						        	
						        },{ 
						        	sortable : true,
						        	autoWidth : true,
						        	dataIndex : "user",
						        	header : "登录帐号",
						        	renderer : function(val) {
										if (val !=null && val!='') {
											return val.loginName;
										} else {
											return '';
										}
									},
						        	width : 50,
						        	align:'center'
						        },{ 
						        	sortable : true,
						        	autoWidth : true,
						        	dataIndex : "dutyNo",
						        	header : "工号",
						        	width:60,
						        	align:'center'
						        },{ 
						        	sortable : true,
						        	autoWidth : true,
						        	dataIndex : "gender",
						        	header : "性别",
						        	width : 35,
						        	align:'center',
						        	renderer : function(value) {
										if (value == 1) {
											return '男';
										} else {
											return '女';
										}
									}
						        	
						        },{ 
						        	sortable : true,
						        	autoWidth : true,
						        	dataIndex : "duty",
						        	header : "职务",
						        	width : 50,
						        	align:'center'
						        },{ 
						        	sortable : true,
						        	autoWidth : true,
						        	dataIndex : "phone",
						        	header : '<div style=text-align:center;">手机</div>',
						        	width : 65
						        },{ 
						        	sortable : true,
						        	autoWidth : true,
						        	dataIndex : "email",
						        	header : '<div style=text-align:center;">Email</div>',
						        	width : 65
						        }, 
							    {
							    header:'操作',
							    autoWidth:true,
							    width:120,
								renderer : function(v, c, r) {
									var s = '<a href="javascript:void(0);"  onclick="personView.passwd('+r.data.user.id+',\''+r.data.user.loginName+'\',\''+r.data.name+'\');">【重置密码】</a>';
									    s+= '<a href="javascript:void(0);"  onclick="personView.grant('+r.data.user.id+',\''+r.data.name+'\');">【角色授权】</a>';
									    //s+= '<a href="javascript:void(0);"  onclick="personView.grantUser('+v+',\''+r.data.name+'\');">【人员授权】</a>';
									return s;
								},
								align:'center'
						    }
								
							],
						tbar : personView.createTbar(),
						bbar : {
							id : 'page',
							xtype : 'pageinfobar',
							pageSize : 50,
							store : store,
							pageMethod : personView.queryResItem
						}
			  });
		},
		
		passwd : function(id,accountName,userName){
			this.onUserAddOrEditInit('account');
			accountwin.setTitle('<center>重置[ '+userName+' ]帐号</center>');
			accountwin.show();
			Ext.getCmp('id').setValue(id);
			Ext.getCmp('loginName').setValue(accountName);
			
		},
		
		grant : function(v,n){
			this.onUserAddOrEditInit('userRole');
			this.roleGrant(v);
			this.setRoleWinShow(v,n);
		},
		
		grantUser : function(v,n){
			 this.onUserAddOrEditInit('userrights');
			 grantUserId = v;
			 grantwin.setTitle('用户[ '+n+' ]授权');
			 grantwin.show();
		},
		
		proxy : function(v,n){
			this.onUserAddOrEditInit('userproxy');
			this.userproxy(v);
			this.setUserWinOnShow(v,n);
		},
		
		 userproxy : function(v){
	    	    userstore.removeAll();
	    	    usersecondGridStore.removeAll();
	    	    usersecondGridStore.load( {
					params : {
						"user.id" : v
					}
				});
	        userwin.show();
	    },
	    
	    userqueryResItem : function(v){
			  if(!v) v = Ext.getCmp('userpage').pageSize;
		      userstore.load( {
				params : {
					"page.start" : 0,
					"page.limit" : v
				}
			});
	   },
	    
	    setUserWinOnShow : function(userId,n){
	     	  userwin.on('show',function(){
//		   	        var record = grid.getSelectionModel().getSelected();
		   	        userwin.setTitle('[ '+n+' ]工作代理');
//		   	        var userId = record.get('userid');
		   	        userstore.setBaseParam('user.id',userId);
				    personView.userqueryResItem();
			        var firstGridDropTargetEl =  usergrid.getView().scroller.dom;
			        var firstGridDropTarget = new Ext.dd.DropTarget(firstGridDropTargetEl, {
			                ddGroup    : 'userfirstGridDDGroup',
			                notifyDrop : function(ddSource, e, data){
			                        var records =  ddSource.dragData.selections;
			                        Ext.each(records, ddSource.grid.store.remove, ddSource.grid.store);
			                        //异步删除
			                        Ext.Ajax.request({
											url : cfg.cxt+'/user_deleteUserProxy.do',
											success : function(response) {
												var rt = Ext.decode(response.responseText);
												if (!rt.success){
													bangni.ajaxError(response);
												}
											},
								            failure : bangni.ajaxError,
											params : {
												"user.id" : userId,
												"proxyuserid" : records[0].id
											}
										});
			                        return true;
			                }
			        });
			
			        var secondGridDropTargetEl = usersecondGrid.getView().scroller.dom;
			        var secondGridDropTarget = new Ext.dd.DropTarget(secondGridDropTargetEl, {
			                ddGroup    : 'usersecondGridDDGroup',
			                notifyDrop : function(ddSource, e, data){
			                        var records =  ddSource.dragData.selections;
			                        var s =  usersecondGrid.store;
			                        if(s.indexOfId(records[0].id)>-1)return false; 
			                        s.add(records);
			                        //异步添加
			                        Ext.Ajax.request({
											url : cfg.cxt+'/user_updateUserProxy.do',
											success : function(response) {
												var rt = Ext.decode(response.responseText);
												if (!rt.success){
													bangni.ajaxError(response);
												}
											},
								            failure : bangni.ajaxError,
											params : {
												"user.id" : userId,  //代理人id
												"proxyuserid" : records[0].id //被代理人Id
											}
										});
			                        return true;
			                }
		        });
		    });
	     },
		
		createTbar : function() {
			if(queryRole){
				tbarOpr.push('->');
				tbarOpr.push(
						new Ext.form.TextField( {
						id : 'pname',
						emptyText : '请输入人员名称',
						enableKeyEvents : true,
						listeners : {
							specialkey : function(field, e) {
								if (e.getKey() == Ext.EventObject.ENTER) {
									personView.queryResItem();
								}
							}
						},
						width : 120
						})
						);
				tbarOpr.push({
					text : '查询',
					iconCls : 'previewIcon',
					handler : function() {
						personView.queryResItem();
					}
				}, '-'
				, {
				text : '刷新',
					iconCls : 'arrow_refreshIcon',
					handler : function() {
						personView.queryResItem();
					}
				} );
			}
			return tbarOpr;
			
		},
		
		createOrgTree : function() {
			return new Ext.tree.TreePanel( {
				loader : new Ext.tree.TreeLoader( {
					dataUrl :  cfg.cxt+'/org/tree.action',
					  listeners:{
		                beforeload:function(treeLoader, node){
		                    this.baseParams={  
		                        nodeId:node.attributes.id
		                    };
		                },
		                loadexception : bangni.storeLoadError
		            }
				}),
				root : new Ext.tree.AsyncTreeNode( {  
					text : '单位(机构)管理',
					expanded : true,
					id : '0'
				}),
				title : '',
				applyTo : 'orgTreeDiv',
				autoScroll : false,
				animate : false,
				useArrows : false, 
				border : false
			});
		},
		
		queryResItem : function(v) {
			if(!v) v = Ext.getCmp('page').pageSize;
		    store.load( {
				params : {
					"page.start" : 0,
					"page.limit" : v
				}
			});
		},
		
		clearForm : function(pForm) {
			var formItems = pForm.items['items'];
		    for (i = 0; i < formItems.length; i++) {
		        element = formItems[i];
		        if(element.xtype == 'radiogroup')continue;
		        element.setValue('');
		        element.reset(); // 避免出现红色波浪线
		    };
		},
		
		addInit : function() {
			this.onAddOrEditInit();
			var flag = Ext.getCmp('windowmode').getValue();
			if (typeof (flag) != 'undefined') {
				formPanel.form.getEl().dom.reset();
			} else {
				this.clearForm(formPanel.getForm());
			}
			var selectModel = orgTree.getSelectionModel();
			var selectNode = selectModel.getSelectedNode();
			if(selectNode.attributes.id!=0){
				Ext.getCmp('orgId').setValue(selectNode.attributes.id);
				Ext.getCmp('companyId').setValue(this.loadCompanyId(selectNode));
			}else{
				Ext.Mytip.msg('提示', '请先选择单位(机构名称)！');
				return;
			}
			Ext.getCmp('orgName').setValue(selectNode.attributes.text);
			Ext.getCmp('password').setVisible(true);
			Ext.getCmp('username').setVisible(true);
			win.setTitle('<center>新增人员信息</center>');
			Ext.getCmp('windowmode').setValue('add');
			win.show();
		},
		
		editInit : function() {
			var sm = grid.getSelectionModel();
			if(sm.getCount() == 0){
				Ext.Mytip.msg('提示', '请先选择要修改的记录！');
				return;
			}
			if(sm.getCount() > 1){
				Ext.Mytip.msg('提示', '请选择一条记录修改！');
				return;
			}
			this.onAddOrEditInit();
			var record = sm.getSelected();
			formPanel.getForm().loadRecord(record);
			Ext.getCmp('username').setValue(record.data.user.loginName);
			Ext.getCmp('username').setVisible(false);
			Ext.getCmp('password').setValue(record.data.user.pwd);
			Ext.getCmp('password').setVisible(false);
			Ext.getCmp('userId').setValue(record.data.user.id);
			Ext.getCmp('orgId').setValue(record.data.org.id);
			Ext.getCmp('orgName').setValue(record.data.org.name);
			win.setTitle('<center>修改人员信息</center>');
			win.show();
		},
		
		onAddOrEditInit : function(){
			if(!formPanel){
				formPanel = personForm.createFormPanel();
			}
			if(!win){
				win = personForm.createWindow();
			}
		},
		
		onUserAddOrEditInit : function(type){
			switch(type) {
				case 'account' : {
				     if(!accountPanel){
						 accountPanel = userAccountForm.createAccountFormPanel();
					 } 
					 if(!accountwin){
					 	 accountwin = userAccountForm.createAccountWindow();
					 }
				 } break;
				 
				 case 'userRole' : {
				 	 if(!rolestore){
				 	 	rolestore = userRoleForm.createRoleStore();
				 	 }
				 	 if(!rolegrid){
				 	 	rolegrid =  userRoleForm.createRolegrid();
				 	 }
				 	 if(!secondGridStore){
				 	 	secondGridStore = userRoleForm.createSecondGridStore();
				 	 }
				 	 if(!secondGrid){
				 	 	secondGrid = userRoleForm.createSecondGrid();
				 	 }
				 	 if(!rolewin){
				 	 	rolewin = userRoleForm.createRoleWindow();
				 	 }
				 } break;
				 
				 case 'userrights' : {
				 	 if(!grantmoduleTree){
				 	 	grantmoduleTree =  userRightsForm.createGrantModuleTree();
				 	 	userRightsForm.setGrantModuleTreeClick();
				 	 }
				 	 if(!grantformPanel){
				 	 	grantformPanel =  userRightsForm.createGrantFormPanel();
				 	 }
				 	 if(!grantwin){
				 	 	grantwin = userRightsForm.createGrantWindow();
				 	 	userRightsForm.setGrantWindowOnShow();
				 	 }
				 } break;
				  
				 case 'userproxy' : {
				 	 if(!userstore){
				 	 	userstore =  userProxyForm.createUserStore();
				 	 	userstore.on('beforeload', function() {
							this.baseParams = {
								"user.person.name" : Ext.getCmp('qusername').getValue()
							};
						});
				 	 }
				 	 if(!usergrid){
				 	 	usergrid =  userProxyForm.createUserGrid();
				 	 }
				 	 if(!usersecondGridStore){
				 	 	usersecondGridStore =  userProxyForm.createUserSecondGridStore();
				 	 }
				 	 if(!usersecondGrid){
				 	 	usersecondGrid =  userProxyForm.createUserSecondGrid();
				 	 }
				 	 if(!userwin){
				 	 	userwin = userProxyForm.createUserWindow();
				 	 }
				 } break;
				 
				 default : {
				 	 Ext.Mytip.msg('提示', '初始化操作类型['+type+']不存在！');
				 }
			}
			
		},
		

		roleGrant :  function(v){
    	    secondGridStore.load({
				params : {
					"page.start" : 0,
					"page.limit" : 100, //一个用户的角色，不可能超过100
					"userId" : v
				}
			});
	        rolewin.show();
	    },
	    
		queryRoleItem : function(v){
			if(!v) v = Ext.getCmp('rolepage').pageSize;
			     rolestore.load({
					params : {
						"page.start" : 0,
						"page.limit" : v
					}
			});
		},
		
		setRoleWinShow : function(userId,n) {
			rolewin.on('show',function(){
		   	        rolewin.setTitle('[ '+n+' ]角色授权');
				    personView.queryRoleItem();
			        var firstGridDropTargetEl =  rolegrid.getView().scroller.dom;
			        var firstGridDropTarget = new Ext.dd.DropTarget(firstGridDropTargetEl, {
			                ddGroup    : 'firstGridDDGroup',
			                notifyDrop : function(ddSource, e, data){
			                        var records =  ddSource.dragData.selections;
			                        Ext.each(records, ddSource.grid.store.remove, ddSource.grid.store);
									
			                        //异步删除
			                        Ext.Ajax.request({
											url : cfg.cxt+'/user/deleteUserRole.action',
											success : function(response) {
											    var rt = Ext.decode(response.responseText);
												if (!rt.success){
													bangni.ajaxError(response);
												}
											},
								            failure : bangni.ajaxError,
											params : {
												"userId" : userId,
												"roleId" : records[0].id
											}
										});
			                        return true;
			                }
			        });
			        var secondGridDropTargetEl = secondGrid.getView().scroller.dom;
			        var secondGridDropTarget = new Ext.dd.DropTarget(secondGridDropTargetEl, {
			                ddGroup    : 'secondGridDDGroup',
			                notifyDrop : function(ddSource, e, data){
			                        var records =  ddSource.dragData.selections;
			                        var s =  secondGrid.store;
			                        if(s.indexOfId(records[0].id)>-1)return false; 
			                        s.add(records);
//									var userid = record.get('userid');
			                        //异步添加
			                        Ext.Ajax.request({
											url : cfg.cxt+'/user/updateUserRole.action',
											success : function(response) {
												var rt = Ext.decode(response.responseText);
												if (!rt.success){
													bangni.ajaxError(response);
												}
											},
								            failure : bangni.ajaxError,
											params : {
												"userId" : userId,
												"roleId" : records[0].id
											}
										});
			                        return true;	
			                }
		           });
		     });
		},
		
		subForm : function(url) {
			 var mode = Ext.getCmp('windowmode').getValue();
			 Ext.getCmp('username').setDisabled(false);
			 formPanel.form.submit({
				url : cfg.cxt+url,
				waitTitle : '提示',
				method : 'POST',
				waitMsg : '正在处理数据,请稍候...',
				success : function(form, action) {
					var  msg = action.result;
					if(msg.status==200){
						personView.queryResItem();
						win.hide();
						form.reset();
						if (mode == 'add')
						    Ext.Mytip.msg('提示', '新增成功！');
						else
						    Ext.Mytip.msg('提示', '修改成功！');
					} else{
						 Ext.Mytip.msg('提示', msg.info);
					}
					
				},
				failure : bangni.sumbitError
			});
		},
		
		deleteItem : function() {
			var sm = grid.getSelectionModel();
			if(sm.getCount() == 0){
				Ext.Mytip.msg('提示', '您尚未选择要删除的记记录！');
				return;
			}
			var ids = [];
			sm.each(function(r){
			   ids.push(r.data.id);
			});
			Ext.Msg.wait('正在删除，请稍候...','提示');
			Ext.Msg
			   .confirm(
					'请确认',
					'<span style="color:red"><b>提示：</b>相关用户资源也会删除，确认删除吗？</span>',
					function(btn, text) {
						if (btn == 'yes') {
							Ext.Ajax.request({
								url : cfg.cxt+'/person/del.action',
								success : function(response) {
									 var r = Ext.decode(response.responseText);
									 Ext.Msg.hide();
									 if(r.success){
									 	if(r.status=200){
											 personView.queryResItem();
										 }
											 Ext.Mytip.msg('提示',r.info);
									 } else {
										bangni.ajaxError(response);
									}
								},
								failure : bangni.ajaxError,
								params : {
									"ids" : ids.join(',')
								}
							});
						}
					});
		  },
		  
		  editPermission : function (param,url) {
				param = String.format(param, grantUserId);
				return ajaxSyncCall( url , param);
		  },
		  
		  editOnePermission : function(e,y) {
			    var node  = grantmoduleTree.getSelectionModel().getSelectedNode();
			    var param = 'principalType=User&principalId='+grantUserId+'&moduleId='+node.attributes.id+'&permissionExt='+e+'&yes='+y;
		     	ajaxSyncCall( cfg.cxt+'/acl_addOrUpdatePermission.do',param);
		}
	 }
}();
Ext.onReady(personView.init, personView);